package com.vo;

import com.alibaba.fastjson.JSONObject;
import com.common.utils.MeUtils;
import com.google.protobuf.ByteString;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.util.AttributeKey;

public class NettyClient {

    public static void main(String[] args) throws InterruptedException {
        // 首先，netty通过ServerBootstrap启动服务端
        Bootstrap client = new Bootstrap();
        //第1步 定义线程组，处理读写和链接事件，没有了accept事件
        EventLoopGroup group = new NioEventLoopGroup();
        client.group(group );
        //第2步 绑定客户端通道  //
        client.channel(NioSocketChannel.class);
        //第3步 给NIoSocketChannel初始化handler， 处理读写事件
        client.handler(new ChannelInitializer<NioSocketChannel>() {  //通道是NioSocketChannel
            @Override
            protected void initChannel(NioSocketChannel channel) throws Exception {
//
//                channel.pipeline().addLast(new ProtobufVarint32FrameDecoder());
////                            设置自定义的 消息体
//                channel.pipeline().addLast(new ProtobufDecoder(
//                        ProtoMsg.MessageRequest.getDefaultInstance()
//                ));
//                channel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
//                channel.pipeline().addLast(new ProtobufEncoder());

                channel.pipeline().addLast(new ProtobufVarint32FrameDecoder());
                channel.pipeline().addLast(new ProtobufDecoder(ProtoMsg.MessageRequest.getDefaultInstance()));
                channel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
                channel.pipeline().addLast(new ProtobufEncoder());
//                channel.pipeline().addLast(new StringDecoder());
//                channel.pipeline().addLast(new StringEncoder());

//                // 协议包编码
//                channel.pipeline().addLast(new MessageToMessageEncoder<MessageLiteOrBuilder>() {
//                    @Override
//                    protected void encode(ChannelHandlerContext ctx, MessageLiteOrBuilder msg, List<Object> out) throws Exception {
//                        ByteBuf result = null;
//                        if (msg instanceof MessageLite) {
//                            result = wrappedBuffer(((MessageLite) msg).toByteArray());
//                        }
//                        if (msg instanceof MessageLite.Builder) {
//                            result = wrappedBuffer(((MessageLite.Builder) msg).build().toByteArray());
//                        }
//
//                        // ==== 上面代码片段是拷贝自TCP ProtobufEncoder 源码 ====
//                        // 然后下面再转成websocket二进制流，因为客户端不能直接解析protobuf编码生成的
//
//                        WebSocketFrame frame = new BinaryWebSocketFrame(result);
//                        out.add(frame);
//                    }
//                });
                channel.pipeline().addLast(new NettyClientHandler());
            }
        });

        //连接服务器
//        ChannelFuture future = client.connect("192.168.3.232", 8007).sync();
        ChannelFuture future = client.connect("localhost", 28888).sync();


//        Thread.sleep(50000);

        //发送数据给服务器
        User user = new User();
        user.setAge(12);
        user.setId(1);
        user.setName("名字，姓名");
//        future.channel().writeAndFlush(JSONObject.toJSONString(user)+"\r\n");

        for(int i=0;i<5000;i++){
            ProtoMsg.MessageRequest.Builder builder = ProtoMsg.MessageRequest.newBuilder();
            builder.setKey("key十多首来"+"");


//            String r1 = MeUtils.imgBase64("http://webquoteklinepic.eastmoney.com/GetPic.aspx?nid=0.300745&UnitWidth=-6&imageType=KXL&EF=&Formula=RSI&AT=1&&type=M5");
//            System.out.println(r1.length());
            user.setName("名字，姓名sjkdlfjls  计算机技术李老师6 #");
            String msg = JSONObject.toJSONString(user);

            ByteString byt=ByteString.copyFrom(msg.getBytes());
            builder.setData(byt);
            builder.setStatus((5000-i)+"");
//            System.out.println(JSONObject.toJSONString(builder));
            ProtoMsg.MessageRequest build = builder.build();
            future.channel().writeAndFlush(build);
            Thread.sleep(1000);
        }


        for(int i=0;i<5000;i++){
            ProtoMsg.MessageRequest.Builder builder = ProtoMsg.MessageRequest.newBuilder();
            builder.setKey(i+"");
            String msg = JSONObject.toJSONString(user);
//            builder.setData(msg);
//            builder.setStatus((5000-i)+"");
            ProtoMsg.MessageRequest build = builder.build();
            future.channel().writeAndFlush("build"+i);


//            String response = "I am ok!"+i;
//            // 在当前场景下，发送的数据必须转换成ByteBuf数组
//            ByteBuf encoded = future.channel().alloc().buffer(4 * response.length());
//            encoded.writeBytes(response.getBytes());
//            future.channel().write(encoded);
//            future.channel().flush();
            Thread.sleep(1000);
        }
        //当通道关闭了，就继续往下走

        //接收服务端返回的数据
        AttributeKey<String> key = AttributeKey.valueOf("ServerData");
        Object result = future.channel().attr(key).get();
        System.out.println(result.toString());


    }
}
